package com.zb.springcloud.controller;

import com.zb.springcloud.entities.CommonResult;
import com.zb.springcloud.entities.Payment;
import com.zb.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
public class PaymentController {
    @Resource
    PaymentService paymentService;
    @Resource
    private DiscoveryClient discoveryClient;
    @Value("${server.port}")
    private String serverPort;
    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int i = paymentService.create(payment);
        if (i > 0){
            return  new CommonResult(200, "插入数据库成功"+serverPort, i);
        }else {
            return  new CommonResult(400, "插入数据库失败", null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        if (payment  != null){
            return  new CommonResult(200, "查询成功"+serverPort, payment);
        }else {
            return  new CommonResult(400, "没有对应记录，查询ID ：" + id, null);
        }
    }
    @GetMapping("/payment/getDiscoverClient")
    public Object getDiscoverClient(){
        List<String> services = discoveryClient.getServices();
        services.forEach(log::info);
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(x->{
            log.info(x.getServiceId()+"\t"+x.getHost()+ "\t"+x.getPort()+"\t"+x.getUri());
        });
        return discoveryClient;
    }
    @GetMapping("/payment/lb")
    public String getPaymentLb(){
        return serverPort;
    }
}
